package utils;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class FileOpt {
	/**
	 * 将json字符串转换成对象
	 * @param json
	 * @param c
	 * @return
	 */
	public static <T> T toObj(String json,Class<T> c){
		JSONObject jsonObj = JSONObject.fromObject(json);
		return (T)JSONObject.toBean(jsonObj, c);
	}
	/**
	 * 将json字符串转换成List集合
	 * @param json
	 * @param c
	 * @return
	 */
	public static <T> List<T> toList(String json,Class<T> c){
		JSONArray jsonArr = JSONArray.fromObject(json);
		return (List<T>)JSONArray.toList(jsonArr, c);
	}
	/**
	 * 读取文件返回文件内容
	 * @param path
	 * @return
	 */
	public static String read(String path){
		StringBuffer sb = new StringBuffer();
		FileReader fr = null;   
        try {   
        	fr = new FileReader(path);   
            long begin3 = System.currentTimeMillis(); 
			char[] ch = new char[128];	//一次读取128个字符
			int len = 0;
			while((len = fr.read(ch,0, ch.length)) != -1){
				sb.append(ch, 0, len);
			}
			fr.close();
            long end3 = System.currentTimeMillis();   
            System.out.println("FileReader执行耗时:" + (end3 - begin3) + " 豪秒");   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
            try {   
            	fr.close();   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
        return sb.toString();
	}
	public static void writer(String content,String dir,String name){
		File file = new File(dir);
		if(!file.isDirectory()){
			file.mkdirs();

		}
		writer(content,dir+name);
	}
	/**
	 * 将制定内容写入指定路劲文件
	 * @param content
	 * @param path
	 */
	public static void writer(String content,String path){
		FileWriter fw = null;   
        try {   
            fw = new FileWriter(path);   
            long begin3 = System.currentTimeMillis();   
            fw.write(content);   
            fw.close();   
            long end3 = System.currentTimeMillis();   
            System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 豪秒");   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
            try {   
                fw.close();   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
	}

}
